package com.ziytek.web.citizen.model.bean;

import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.constant.ServerConstant;
import lombok.Data;

/**
 * @author fenghx
 * @version v1.0
 * @className ChargeAndDischargeControlProtocol
 * @descripton 充放电控制协议
 * @date 2023/4/27 15:49
 **/
@Data
public class IssuedProtocol {
    private String header = "BB";

    /**
     * 通信板地址
     */
    private String cabinetAddress = "00";
    /**
     * CMD命令类型
     * 0x01 - LED灯控制
     * 0x02 - 充放电控制设置
     * 0x03 - 数据查询
     * 0x04 - 设置参数
     * 0x06 - 获取分容结果
     * 0x07 - 业务请求
     * 0x08 - 业务请求响应
     * 0x09 - 分容结果请求
     * 0x10 - 分容结果响应
     */
    private String dataType = ServerConstant.CMD_TYPE_CHARGE_DISCHARGE_CONTROL;
    /**
     * 有效数据长度
     */
    private String dataLen = "0018";

    /**
     * 负载数据
     */
    private String loadData;

    /**
     * 消息唯一标识 2字节  0x0000-0xFFFF
     */
    private String messageUniqueIdentifier;


    private String xor;
    /**
     * 数据尾 固定 CC
     */
    private String dataTail = "CC";

    private String getSeparatorData() {
        String d = this.loadData;

        StringBuilder buffer = new StringBuilder();
        for (int i = NumConstant.INT_ZERO; i < d.length() / NumConstant.INT_TWO; i++) {
            if (i == ((d.length() / NumConstant.INT_TWO) - NumConstant.INT_ONE)) {
                buffer.append(d, i * NumConstant.INT_TWO, (i + NumConstant.INT_ONE) * NumConstant.INT_TWO);
            } else {
                buffer.append(d, i * NumConstant.INT_TWO, (i + NumConstant.INT_ONE) * NumConstant.INT_TWO).append(ServerConstant.DATA_SEPARATOR_BLANK_SPACE);
            }
        }

        return buffer.toString();
    }

    public String getAllData() {
        return this.header + ServerConstant.DATA_SEPARATOR_BLANK_SPACE
                + this.cabinetAddress + ServerConstant.DATA_SEPARATOR_BLANK_SPACE
                + this.dataType + ServerConstant.DATA_SEPARATOR_BLANK_SPACE
                + this.dataLen + ServerConstant.DATA_SEPARATOR_BLANK_SPACE
                + this.getSeparatorData() + ServerConstant.DATA_SEPARATOR_BLANK_SPACE
                + this.messageUniqueIdentifier + ServerConstant.DATA_SEPARATOR_BLANK_SPACE
                + this.xor + ServerConstant.DATA_SEPARATOR_BLANK_SPACE
                + this.dataTail;
    }
}
